"""
应用程序入口模块
"""
import sys
from PyQt6.QtWidgets import QApplication
from .main_window import MainWindow
from biz.script_runner import get_script_runner
from biz.scheduled_price_analyzer import ScheduledPriceAnalyzer
from biz.refresh_account_uk import AccountUkRefresher
from biz.track_report_scheduler import TrackReportScheduler
from biz.goods_score_analyzer import GoodsScoreAnalyzer
from biz.scheduled_history_data_fetcher import ScheduledHistoryDataFetcher
from biz.steam_trade_manager import start_trade_status_refresh, stop_trade_status_refresh
# from biz.kline_collect_and_analyze_scheduler import get_kline_scheduler
from com.utils.logger import get_logger
from com.db.migrations.add_min_profit_rate_to_tasks import run_migration

logger = get_logger("App")

def run_app():
    """运行应用程序"""
    # 执行数据库迁移
    try:
        migration_result = run_migration()
        if migration_result:
            logger.info("数据库迁移成功完成")
        else:
            logger.warning("数据库迁移未执行或失败")
    except Exception as e:
        logger.error(f"执行数据库迁移时出错: {str(e)}")
    
    # 获取脚本运行器实例，但不启动脚本
    script_runner = get_script_runner()
    # script_runner.start_active_scripts()  # 注释掉自动启动脚本的代码
    
    # 初始化并启动定时价格分析器
    price_analyzer = ScheduledPriceAnalyzer(interval_minutes=30)
    try:
        price_analyzer.start()
        logger.info("定时价格分析器已启动")
    except Exception as e:
        logger.error(f"启动定时价格分析器失败: {str(e)}")
    
    # 初始化并启动账号UK刷新器
    uk_refresher = AccountUkRefresher()
    try:
        uk_refresher.start_background_refresh()
        logger.info("账号UK定时刷新器已启动")
    except Exception as e:
        logger.error(f"启动账号UK定时刷新器失败: {str(e)}")
        
    # 初始化并启动定时上报任务
    # track_reporter = TrackReportScheduler()
    # try:
    #     track_reporter.start()
    #     logger.info("定时上报任务已启动")
    # except Exception as e:
    #     logger.error(f"启动定时上报任务失败: {str(e)}")
        
    # 初始化并启动商品评分定时分析
    # score_analyzer = GoodsScoreAnalyzer(interval_hours=1)
    # try:
    #     score_analyzer.start()
    #     logger.info("商品评分定时分析已启动")
    # except Exception as e:
    #     logger.error(f"启动商品评分定时分析失败: {str(e)}")
    
    # 初始化并启动历史数据定时抓取器
    # history_fetcher = ScheduledHistoryDataFetcher(interval_hours=2)
    # try:
    #     history_fetcher.start()
    #     logger.info("历史数据定时抓取器已启动")
    # except Exception as e:
    #     logger.error(f"启动历史数据定时抓取器失败: {str(e)}")
    
    # 初始化并启动Steam交易状态刷新定时任务
    # try:
    #     start_trade_status_refresh()
    #     logger.info("Steam交易状态刷新定时任务已启动")
    # except Exception as e:
    #     logger.error(f"启动Steam交易状态刷新定时任务失败: {str(e)}")
    
    # 初始化并启动K线数据采集和分析定时器
    # kline_scheduler = get_kline_scheduler(interval_hours=2)
    # try:
    #     kline_scheduler.start()
    #     logger.info("K线数据采集和分析定时器已启动")
    # except Exception as e:
    #     logger.error(f"启动K线数据采集和分析定时器失败: {str(e)}")
    
    # 创建并运行应用
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    
    # 注册退出时的清理函数
    def cleanup():
        # script_runner.stop_all()
        price_analyzer.stop()
        uk_refresher.stop()
        # track_reporter.stop()
        # score_analyzer.stop()
        # history_fetcher.stop()
        # stop_trade_status_refresh()
        # kline_scheduler.stop()  # 停止K线数据采集和分析定时器
        logger.info("应用程序正在退出，已停止所有任务")
    
    app.aboutToQuit.connect(cleanup)
    
    sys.exit(app.exec())
